package com.bulletelc.apollopre.module.deal.pay;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.OrderDataBean;
import com.bulletelc.apollopre.entity.PayTypeBean;
import com.bulletelc.apollopre.entity.PrepayIdDataBean;
import com.bulletelc.apollopre.eventbus.EventBusEvent;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.module.main.center.orders.detail.OrderDetailActivity;
import com.bulletelc.apollopre.utils.EncryptUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.CustomListView;
import com.bulletelc.apollopre.widget.FoolBar;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author: lhl
 * date  : 2018/01/21
 * desc  : 支付中心界面
 */

public class PayCenterActivity extends MVPBaseActivity<PayCenterContract.View, PayCenterPresenter> implements PayCenterContract.View,
        View.OnClickListener, AdapterView.OnItemClickListener, FoolBar.ClickCallback {

    // views
    private FoolBar foolBar;
    private TextView tvTimeLeft;
    private TextView tvOrderCode;
    private TextView tvGrandTotal;
    private CustomListView lvPayType;
    private Button btnConfirmPay;

    // data
    private OrderDataBean orderDataBean;
    private PayTypeAdapter adapter;
    private List<PayTypeBean> payTypeBeans;
    private int lastPosition;

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this); //取消注册事件
    }

    @Override
    public int getLayoutRes() {
        return R.layout.pay_center_activity;
    }

    @Override
    public void assignViews() {
        foolBar = findView(R.id.flBar);
        foolBar.setTitle(this.getResources().getString(R.string.order_pay_center));
        tvTimeLeft = (TextView) findViewById(R.id.tvTimeLeft);
        tvOrderCode = (TextView) findViewById(R.id.tvOrderCode);
        tvGrandTotal = (TextView) findViewById(R.id.tvGrandTotal);
        lvPayType = (CustomListView) findViewById(R.id.lvPayType);
        btnConfirmPay = findView(R.id.btnConfirmPay);
    }

    @Override
    public void setListener() {
        foolBar.setClickCallback(this);
        btnConfirmPay.setOnClickListener(this);
        lvPayType.setOnItemClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        orderDataBean = (OrderDataBean) intent.getSerializableExtra(IntentCode.EXTRA_KEY_ORDER_DATA);
        tvOrderCode.setText(orderDataBean.getCode());
        tvGrandTotal.setText("¥" + MyUtil.format2(orderDataBean.getGrand_total()));
        payTypeBeans = new ArrayList<>();
        adapter = new PayTypeAdapter(this, payTypeBeans);
        lvPayType.setAdapter(adapter);
        presenter.getPayType();

    }

    @Override
    protected PayCenterPresenter createPresenter() {
        return new PayCenterPresenter();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btnConfirmPay:
                confirmPay();
                break;
        }
    }

    @Override
    public void onSuccessPayType(List<PayTypeBean> payTypeBeans) {
        if (payTypeBeans != null) {
            this.payTypeBeans.clear();
            this.payTypeBeans.addAll(payTypeBeans);
            adapter.notifyDataSetChanged();
        } else {
            Toast.makeText(this, "数据有误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailPayType(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorPayType(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    @Override
    public void onSuccessPrepayId(PrepayIdDataBean prepayIdDataBean) {
        if (prepayIdDataBean != null) {
            wxPayReq(prepayIdDataBean);
        } else {
            Toast.makeText(this, "数据有误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailPrepayId(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorPrepayId(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position != lastPosition) {
            for (int i = 0, size = payTypeBeans.size(); i < size; i++) {
                if (position == i) {
                    payTypeBeans.get(i).setIs_default(1);
                    lastPosition = position;
                } else {
                    payTypeBeans.get(i).setIs_default(0);
                }
            }
            adapter.notifyDataSetChanged();
        }
    }

    /**
     *  接收微信分享处理事件
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEvent event) {
        switch (event.getWxPayErrCode()) {
            case 0: //支付成功
                Toast.makeText(this, "成功支付", Toast.LENGTH_SHORT).show();

                //跳转到订单详情页
                Intent intent = new Intent(this, OrderDetailActivity.class);
                intent.putExtra(IntentCode.EXTRA_KEY_ORDER_ID, orderDataBean.getId());
                startActivity(intent);

                finish();
                break;

            case -1://失败
                Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
                // do nothing
                break;

            case  -2: //用户取消
                Toast.makeText(this, "取消支付", Toast.LENGTH_SHORT).show();
                // do nothing
                break;
        }

    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    /**
     * 确认支付
     */
    private void confirmPay() {
        getPrepayId();
    }

    /**
     * 获取预付单号
     */
    private void getPrepayId() {
        String paymentMethodCode = null;
        for (int i = 0, size = payTypeBeans.size(); i < size; i++) {
            if (payTypeBeans.get(i).getIs_default() == 1) {
                paymentMethodCode = payTypeBeans.get(i).getCode();
            }
        }

        String json = null;
        JSONObject object = new JSONObject();
        JSONObject subObj = new JSONObject();
        try {
            subObj.put("eshop_id", "1");
            subObj.put("order_id", orderDataBean.getId());
            subObj.put("order_code", orderDataBean.getCode());
            subObj.put("payment_method_code", paymentMethodCode);
            subObj.put("signature_code", orderDataBean.getCode());
            subObj.put("signature", EncryptUtil.sha256(orderDataBean.getCode()));
            object.put("PayOrderForm", subObj);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (json != null) {
            presenter.getPrepayId(json, MyApplication.getToken());
        } else {
            Toast.makeText(this, "请求的参数有误", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 调起微信支付
     * @param prepayIdDataBean
     */
    private void wxPayReq(PrepayIdDataBean prepayIdDataBean) {
        IWXAPI wxApi = MyApplication.getInstance().getIwxapi();
        if (wxApi.isWXAppInstalled() && wxApi.isWXAppSupportAPI()) {
            PayReq request = new PayReq();
            request.appId = prepayIdDataBean.getAppid();
            request.partnerId = prepayIdDataBean.getPartnerid();
            request.prepayId = prepayIdDataBean.getPrepayid();
            request.packageValue = prepayIdDataBean.getPackageX(); //Sign=WXPay
            request.nonceStr = prepayIdDataBean.getNoncestr();
            request.timeStamp = String.valueOf(prepayIdDataBean.getTimestamp());
            request.sign = prepayIdDataBean.getSign();

            wxApi.sendReq(request);
        } else {
            Toast.makeText(this, "请安装最新版微信", Toast.LENGTH_SHORT).show();
        }


    }

}
